package com.easy.gateway.filter;

import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.easy.common.service.IRedisService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

//@Component
public class GlobalAuthFilter implements GlobalFilter, Ordered {
    @DubboReference
    IRedisService redisService;
    /**
     * 白名单直接放行的地址
     */
    private static final List<String> WHITE_LIST = Arrays.asList(
            "/auth/login",
            "/auth/loginout"
    );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //当前请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取访问路径
        String path = request.getURI().getPath();
        // 白名单直接放行
        if (WHITE_LIST.stream().anyMatch(path::contains)) {
            //放行
            return chain.filter(exchange);
        }

        //拿取token
        String token = extractToken(request);
        //校验token
        if (token == null) {
            return unauthorizedResponse(exchange, "认证失效");
        }
        //通过token获取权限信息
        String allpermission=(String)redisService.get(token);
        //将权限信息设置到请求对象中
        ServerHttpRequest modifiedRequest = exchange.getRequest().mutate()
                .header("X-User-Permissions", allpermission)
                .build();
        //放行
        return chain.filter(exchange.mutate().request(modifiedRequest).build());

    }

    private String extractToken(ServerHttpRequest request) {
        String bearerToken = request.getHeaders().getFirst("Authorization");
        if (StringUtils.hasText(bearerToken)) {
            return bearerToken;
        }
        return null;
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {

        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json");
        return response.writeWith(Mono.just(response.bufferFactory()
                .wrap(new JsonObject().toString().getBytes(StandardCharsets.UTF_8))));
    }

    @Override
    public int getOrder() {
        return -100; // 最高优先级
    }
}
